package com.owo.springboot.service;

import com.owo.springboot.dto.CarPlateResult;
import com.owo.springboot.dto.EndOrderRequest;
import com.owo.springboot.dto.ReservationInfoRequest;
import com.owo.springboot.dto.ReservationInfoResponse;
import com.owo.springboot.entity.Reservation;
import com.owo.springboot.repository.ReservationRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@RequiredArgsConstructor
public class ReservationService {
    private final ReservationRepository reservationRepository;

    @Value("${upload.path:uploads/}")
    private String uploadPath;

    private final CarPlateService carPlateService;

    public String uploadImage(MultipartFile file) throws IOException {
        // 确保上传目录存在
        Path uploadDir = Paths.get(uploadPath);
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = getFileExtension(originalFilename);
        String uniqueFileName = UUID.randomUUID().toString() + "." + fileExtension;
        Path filePath = uploadDir.resolve(uniqueFileName);

        // 保存文件
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

        // 返回访问URL（根据实际部署情况调整）
        return "/uploads/" + uniqueFileName;
    }

    private String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf('.') == -1) {
            return "jpg"; // 默认使用jpg
        }
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }

    public CarPlateResult recognizePlate(MultipartFile image) throws IOException {
        return carPlateService.recognizePlate(image);
    }

    public ReservationInfoResponse reservate(ReservationInfoRequest request) {
        try {
            // 处理日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime startTime = LocalDateTime.parse(request.getStartTime(), formatter);
//            LocalDateTime endTime = LocalDateTime.parse(request.getEndTime(), formatter);
//
//            // 验证时间逻辑
//            if (startTime.isAfter(endTime)) {
//                return ReservationInfoResponse.builder()
//                        .success(false)
//                        .message("开始时间不能晚于结束时间")
//                        .build();
//            }
//
//            // 计算时间差（以小时为单位）
//            Duration duration = Duration.between(startTime, endTime);
//            long hours = duration.toHours();
//
//            String price = String.valueOf(hours * 5);

            // 保存预约信息
            String reservationId = UUID.randomUUID().toString();
            Reservation reservation = Reservation.builder()
                    .id(reservationId)
                    .userId(request.getUserId())
                    .start_time(startTime)
//                    .end_time(endTime)
                    .plateNumber(request.getPlateNumber())
                    .plateUrl(request.getPlateUrl())
                    .plateParkId(request.getPlatePackId())
//                    .price(price)
                    .build();

            reservationRepository.save(reservation);

            return ReservationInfoResponse.builder()
                    .success(true)
                    .message("预约成功")
                    .reservationId(reservationId)
                    .startTime(request.getStartTime())
//                    .endTime(request.getEndTime())
                    .plateNumber(request.getPlateNumber())
                    .plateUrl(request.getPlateUrl())
                    .userId(request.getUserId())
                    .plateParkId(request.getPlatePackId())
//                    .price(price)
                    .build();
        } catch (Exception e) {
            return ReservationInfoResponse.builder()
                    .success(false)
                    .message("预约失败: " + e.getMessage())
                    .build();
        }
    }

    public Map<String, Object> getParkStatus() {
        List<String> plateParkIds = reservationRepository.findAllByPlateParkIdNotNull();

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "获取停车场状态成功");
        result.put("plateParkIds", plateParkIds);
        return result;
    }

    public List<String> findAllIdsByUserId(String userId) {
        return reservationRepository.findAllIdsByUserId(userId);
    }

    public List<Reservation> getAllReservation(String userId) {
        try {
            // 直接获取用户的所有预订
            List<Reservation> reservations = reservationRepository.findAllByUserId(userId);
            return reservations;
        } catch (Exception e) {
            return java.util.Collections.emptyList();
        }
    }

    public Reservation endOrder(EndOrderRequest request) {
        Optional<Reservation> optionalReservation = reservationRepository.findById(request.getOrderId());

        if (optionalReservation.isPresent()) {
            Reservation reservation = optionalReservation.get();
            reservation.setEnd_time(request.getEndTime());

            Duration duration = Duration.between(reservation.getStart_time(), reservation.getEnd_time());
            double hours = duration.toHours() + (double) duration.toMinutesPart() / 60;

            double price = Math.ceil(hours * 2) / 2 * 10; // 每半小时5元，向上取整

            reservation.setPrice(String.format("%.2f", price));

            return reservationRepository.save(reservation);
        } else {
            throw new IllegalArgumentException("订单不存在，ID: " + request.getOrderId());
        }
    }
}
